package com.hisan.freeride.common.view;

/**
 * Created by Administrator on 2017/4/3.
 */

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.hisan.freeride.R;
import com.hisan.freeride.common.utils.CollectionUtils;
import com.hisan.freeride.home.activity.RotationActivity;


/**
 * item页底部的webview
 */
public class ItemWebView extends WebView {
    public float oldY;
    private int t;
//    private float oldX;
    private WebSettings webSettings;
    //进度条
    private ProgressBar progressbar;
    //网页title
    private String titlename="";

    private TextView Ttitle=null;


    public String getTitlename() {
        return titlename;
    }

    public ItemWebView(Context context) {
        super(context);
        initWeb(context);
    }

    public ItemWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initWeb(context);
    }

    public ItemWebView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initWeb(context);
    }

    public   void setDrawable(Context context){
        Drawable drawable = context.getResources().getDrawable(R.drawable.progress_bar_states);
        progressbar.setProgressDrawable(drawable);
        addView(progressbar);
    }

    private void initWeb(Context context) {
        progressbar = new ProgressBar(context, null,
                android.R.attr.progressBarStyleHorizontal);
        progressbar.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
                4, 0, 0));

        //加载加载进度条监听
        setWebChromeClient(new WebChromeClient());
        webSettings = this.getSettings();
             /* 设置支持Js,必须设置的,不然网页基本上不能看 */
        webSettings.setJavaScriptEnabled(true);
//            /* 大部分网页需要自己保存一些数据,这个时候就的设置下面这个属性 */
//        webSettings.setDomStorageEnabled(true);
         /* 设置为使用webview推荐的窗口 */
        webSettings.setUseWideViewPort(true);
        /* 设置网页自适应屏幕大小 ---这个属性应该是跟上面一个属性一起用 */
        webSettings.setLoadWithOverviewMode(true);
        /* 设置是否允许webview使用缩放的功能,我这里设为false,不允许 */
        webSettings.setBuiltInZoomControls(false);
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //关闭webview中缓存
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式
        //这个api仅仅清除自动完成填充的表单数据，并不会清除WebView存储到本地的数据
        this.clearFormData();
        // web内容强制满屏
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        //设置加入网页时不加载外部游览器
        this.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                LogUtils.v("ccc",url);
                view.loadUrl(url);;
                return true;
            }
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                LogUtils.v("ccc","加载开始");
                super.onPageStarted(view, url, favicon);
            }
            @Override
            public void onPageFinished(WebView view, String url) {
                LogUtils.v("ccc","加载结束");
                super.onPageFinished(view, url);
            }
            @TargetApi(Build.VERSION_CODES.M)
            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                LogUtils.v("ccc","加载失败");
                LogUtils.v("ccc",request.getUrl()+":"+error.getErrorCode());
            }
        });
    }

    public WebSettings getWebSettings(){
        return  webSettings;
    }

    //加载服务器的html
    public  void SetData(String tcontent){
        this.loadDataWithBaseURL(null,getHtmlData(tcontent), "text/html", "utf-8", null);
    }

    //加载网页
    public void load(String url, TextView title){
        Ttitle=title;
        if (CollectionUtils.checkURL(url)){
          loadUrl(url);
        }else {
            String html="file:///android_asset/404.html";
            loadUrl(html);
        }

    }

    //加载本地的
    public  void SetHtml(String tcontent){
        this.loadUrl(tcontent);
    }


    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_MOVE:
                float Y = ev.getY();
                float Ys = Y - oldY;
//                float X = ev.getX();

                if (Ys > 0 && t == 0) {
                    getParent().getParent().requestDisallowInterceptTouchEvent(false);
                }
                break;

            case MotionEvent.ACTION_DOWN:
                getParent().getParent().requestDisallowInterceptTouchEvent(true);
                oldY = ev.getY();
//                oldX = ev.getX();
                break;

            case MotionEvent.ACTION_UP:
                getParent().getParent().requestDisallowInterceptTouchEvent(true);
                break;

            default:
                break;
        }
        return super.onTouchEvent(ev);
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        this.t = t;
        super.onScrollChanged(l, t, oldl, oldt);
    }

    public class WebChromeClient extends android.webkit.WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
                progressbar.setVisibility(GONE);
            } else {
                if (progressbar.getVisibility() == GONE)
                    progressbar.setVisibility(VISIBLE);
                progressbar.setProgress(newProgress);
            }
            super.onProgressChanged(view, newProgress);
        }

        //
        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            if (Ttitle!=null){
                Ttitle.setText(title);
            }
//            titlename=title;
        }
    }

    private String getHtmlData(String bodyHTML) {
        String head = "<head>" +
                "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> " +
                "<style>img{max-width: 100%; width:auto; height:auto;}</style>" +
                "</head>";
        return "<html>" + head + "<body>" + bodyHTML + "</body></html>";
    }
}